package com.myStoreorderProvider.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.myStoreorderProvider.entity.AlipayBean;
import com.myStoreorderProvider.service.PayService;
import entity.Outorder;
import entity.Storebill;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import service.mystore.MyStoreorderService;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author oahner
 * @create 2022-04-26 19:06
 */
@Controller
@CrossOrigin
@RequestMapping("alipay")
public class AliPayController {

    private Logger logger=Logger.getLogger(this.getClass());

    @Autowired
    private PayService payService;

    @Autowired
    private MyStoreorderService service;
//    @Resource
//    private OrderService orderService;

    @RequestMapping(value = "/alipay")
    @ResponseBody
    public String alipay(String outTradeNo, String subject, String totalAmount,String storeId) throws AlipayApiException {
        logger.info("支付宝参数：订单号outTradeNo:"+outTradeNo+",订单名称：subject:"+subject+",订单金额totalAmount:"+totalAmount+",storeId:"+storeId);
        String out_trade_no_store_id = outTradeNo+"_"+storeId;
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(out_trade_no_store_id);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody("商品订单");
        System.out.println(alipayBean.toString());
        return payService.aliPay(alipayBean);
    }

    @RequestMapping("/Notify")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        logger.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            /*valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");*/
            params.put(name, valueStr);
        }

        //调用SDK验证签名
//        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type);
        boolean signVerified = AlipaySignature.rsaCheckV1(params,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjYjMLKJMn+z99kG81v8dErLJgEmt78YKpJPBTjlKMNfxNsATU0i223a3Xh8av87XhfoN12X+B4Q+nTsEjOcSE/Im0OQ39X/6wxiW31qzsHe44USFmCO2eMeJwtL0mRFjKIeL8DDhHwvtfgozyiq8WmyXI+k+dHWuRERnMd7YtM/MQmz4atIEMaQEv7Iuzc/QMnFawF8drRjF6023dGsea6DOgMgtr/a3iflYN93o6sOAsVetrU86kK5UoKy8OlQvFIpGuaaeGKjp421mPmhT10YexWI+ANfqQN6QBPMRam0N2hmZBpR2UK9c/hjVzu+oYFNRljYc2CuDir1xDzxW5QIDAQAB", "utf-8", "RSA2");

        //验证成功
        if(signVerified) {
            //商户订单号和门店ID
            String out_trade_no_store_id = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //商户订单号
            String out_trade_no = out_trade_no_store_id.split("_")[0];
            //商户门店号
            String store_id = out_trade_no_store_id.split("_")[1];;

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                logger.info("交易结束");
                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
                Outorder outorder = new Outorder();
                outorder.setOrderNum(out_trade_no);
                outorder.setsId(store_id);
                service.payMyOutorder(outorder);

                //生成账单
                Storebill storebill = new Storebill();
                storebill.setDescription("支出");
                storebill.setStoreId(store_id);
                storebill.setMoney(Double.valueOf(total_amount));
                storebill.setTradeNo(trade_no);
                service.addStoreBill(storebill);

                logger.info("********************** 支付成功(支付宝异步通知) **********************");
                logger.info("* 订单号: {}"+out_trade_no);
                logger.info("* 支付宝交易号: {}"+ trade_no);
                logger.info("* 实付金额: {}"+ total_amount);

            }
            logger.info("支付成功...");
        }else {//验证失败
            logger.info("支付, 验签失败...");
        }
        return "success";
    }


    //同步通知
    @RequestMapping(value = "/pay_return",method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        logger.info("=================同步通知");
        request.setCharacterEncoding("utf-8");//乱码解决，这段代码在出现乱码时使用
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for(String str :requestParams.keySet()){
            String name = str;
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjYjMLKJMn+z99kG81v8dErLJgEmt78YKpJPBTjlKMNfxNsATU0i223a3Xh8av87XhfoN12X+B4Q+nTsEjOcSE/Im0OQ39X/6wxiW31qzsHe44USFmCO2eMeJwtL0mRFjKIeL8DDhHwvtfgozyiq8WmyXI+k+dHWuRERnMd7YtM/MQmz4atIEMaQEv7Iuzc/QMnFawF8drRjF6023dGsea6DOgMgtr/a3iflYN93o6sOAsVetrU86kK5UoKy8OlQvFIpGuaaeGKjp421mPmhT10YexWI+ANfqQN6QBPMRam0N2hmZBpR2UK9c/hjVzu+oYFNRljYc2CuDir1xDzxW5QIDAQAB", "utf-8", "RSA2");

        if(signVerified) {
            //商户订单号
            String out_trade_no_store_id = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //商户订单号
            String out_trade_no = out_trade_no_store_id.split("_")[0];
            //商户门店号
            String store_id = out_trade_no_store_id.split("_")[1];;

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
//            orderService.zhifusuccess(out_trade_no);
            Outorder outorder = new Outorder();
            outorder.setOrderNum(out_trade_no);
            outorder.setsId(store_id);
            service.payMyOutorder(outorder);

            //生成账单
            Storebill storebill = new Storebill();
            storebill.setDescription("支出");
            storebill.setStoreId(store_id);
            storebill.setMoney(Double.valueOf(total_amount));
            storebill.setTradeNo(trade_no);
            service.addStoreBill(storebill);

            request.getSession().setAttribute("userid",request.getSession().getAttribute("userid"));
            logger.debug("======================验签成功-跳转到成功后页面");
            //跳转至支付成功后的页面
            return "redirect:http://192.168.0.15:8080";
        }else {
            logger.error("======================验签失败-跳转到充值页面让用户重新充值");
            return "redirect:http://192.168.0.15:8080";
        }

    }


    /**
     * 获取request中的参数集合转Map
     * Map<String,String> parameterMap = RequestUtil.getParameterMap(request)
     * @param request
     * @return
     */
    @ResponseBody
    public Map<String, String> getParameterMap(HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }


}
